package listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import javax.servlet.http.HttpSessionBindingEvent;

@WebListener()
public class UserCountListener implements HttpSessionListener{

    public void sessionCreated(HttpSessionEvent se) {
        /* 当Session创建出来的时候，执行这个方法+1*/
//        ctx是存在线人数数据的地方
        ServletContext ctx = se.getSession().getServletContext();
        Integer count = (Integer)ctx.getAttribute("OnlineCount");
        if (count == null){
            count=0;
        }
        count++;
        ctx.setAttribute("OnlineCount",count);
    }

    public void sessionDestroyed(HttpSessionEvent se) {
        /* 当Session销毁的时候，就执行这个方法-1 */
        ServletContext ctx = se.getSession().getServletContext();
        Integer count = (Integer)ctx.getAttribute("OnlineCount");
        if (count == null){
            count=0;
        }
        count--;
        ctx.setAttribute("OnlineCount",count);
    }

}
